import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import Layout from '@/layout/index.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      // 首页
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { requiresAuth: true }
      },
      // 直播
      {
        path: 'live',
        name: 'live',
        component: () => import('@/views/live/index.vue'),
        meta: { requiresAuth: true }
      },
      // 实时监管
      {
        path: 'monitor',
        name: 'monitor',
        component: () => import('@/views/monitor/index.vue'),
        meta: { requiresAuth: true }
      },
      // 新建任务（因为新建任务页面是一个独立的全屏页面，所以暂时使用了平级路由）
      {
        path: '/addTask',
        name: 'addTask',
        component: () => import('@/views/monitor/addTask/index.vue'),
        meta: { requiresAuth: true }
      },
      // 数据管理
      {
        path: 'dataManage',
        name: 'dataManage',
        component: () => import('@/views/dataManage/index.vue'),
        meta: { requiresAuth: true }
      },
      // 航线管理
      {
        path: 'airlineManage',
        name: 'airlineManage',
        component: () => import('@/views/airlineManage/index.vue'),
        meta: { requiresAuth: true },
      },
      // 编辑航线（因为编辑航线页面是一个独立的全屏页面，所以暂时使用了平级路由）
      {
        path: '/airlineEdit',
        name: 'airlineEdit',
        component: () => import('@/views/airlineManage/edit/index.vue'),
        meta: { requiresAuth: true }
      },
      // 应用管理
      {
        path: 'appManage',
        name: 'appManage',
        component: () => import('@/views/appManage/index.vue'),
        meta: { requiresAuth: true }
      },
      // 视频测试页面
      {
        path: 'testVideo',
        name: 'testVideo',
        component: () => import('@/views/testVideo/index.vue'),
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && userStore.isAuthenticated) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router